import rclpy
from rclpy.node import Node
from rclpy.timer import Rate
from rclpy.time import Time
from rclpy.duration import Duration
import threading
class RatePyNode(Node):
    def __init__(self):
        super().__init__('rate_py_node')
        self.get_logger().info('rate_py_node创建')
        # self.demo01_rate()
        self.demo02_time()
        self.demo03_duration()
    def demo03_duration(self):
        du1=Duration(seconds=2,nanoseconds=500000000)
        self.get_logger().info("ns1=%d" % du1.nanoseconds)
        pass
    def demo02_time(self):
        t1:Time=Time(seconds=2,nanoseconds=500000000)
        t2:Time=self.get_clock().now()
        self.get_logger().info("s=%.2f,ns=%d" % (t1.seconds_nanoseconds()[0],
                                               t1.seconds_nanoseconds()[1]))
        self.get_logger().info("ns=%d" % t1.nanoseconds)
        self.get_logger().info("s=%.2f,ns=%d" %(t2.seconds_nanoseconds()[0],
                                               t2.seconds_nanoseconds()[1]))
        
        self.get_logger().info("ns=%d"% t2.nanoseconds)
        pass    
    def demo01_rate(self):
        # 如果在主线程中使用 会导致rate.sleep()主线程的阻塞
        # rate=self.create_rate(1.0)
        # count = 0
        # while rclpy.ok():
        #     print(count)
        #     self.get_logger().info(f'第 {count} 次: ++++++++++++++++ rclpy.ok(): {rclpy.ok()}')
        #     self.get_logger().info('++++++++++++++++')
        #     rate.sleep()
        #     self.get_logger().info(f'睡眠后: rclpy.ok(): {rclpy.ok()}')
        # else:
        #     self.get_logger().info('false1111')
        #     print    
        
        self.rate: Rate=self.create_rate(1.0)
        print(type(self.rate))
        thread=threading.Thread(target=self.do_rate)
        thread.start()
    def do_rate(self):
        while rclpy.ok():
            self.get_logger().info('++++++++++++++++')
            self.rate.sleep()
def main():
    rclpy.init()
    rclpy.spin(RatePyNode())
    rclpy.shutdown()


if __name__ == '__main__':
    main()
